package com.neusmart.tongrentang;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Environment;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.neusmart.common.util.L;
import com.neusmart.common.util.ScreenUtil;
import com.neusmart.common.util.TelephoneUtil;
import com.neusmart.common.util.VersionUtil;
import com.neusmart.tongrentang.constants.Key;
import com.neusmart.tongrentang.model.User;

import java.io.File;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by keven on 2016/8/15.
 */
public class F {

    // volley queue
    private static RequestQueue mVolleyQueue;

    private static final boolean isDebug = true;
    public static String domain;

    // 版本信息，进入应用时获取
    public static int VERSION_CODE;
    public static String VERSION_NAME;

    // package name
    public static String packageName;
    // 保存應用信息本地位置
    private static String appDataFolderPath;
    // 圖片文件夾/下載文件夾
    public static String imagesFolder, downloadFolder, webappFolder;

    public static Map<String, String> headers;
    public static String apiKey = "708522cecbed4a0eb2dc3cff8afd6512", appOwnerId = "1";

    // device id
    public static String deviceId;
    public static int mDisplayWidth, mDisplayHeight;

    // shared preferences for saving user info
    private static SharedPreferences mPrefs;
    private static SharedPreferences.Editor mEditor;

    private static final String PREFS_NAME = "yun_xue_che_pref";

    private static Gson mGson;
    public static User mUser;

    // 定位后保存的经纬度
    public static double latitude, longitude;//纬度、经度
    // 定位后保存的身份、城市
    public static String lbsProvince = "", lbsCity = "", location = "";

    public static void init(Context context) {
        if (isDebug)
            L.enableLogging();
        else
            L.disableLogging();
        initDomain(context);
        initAppDataFolderPath(context);
        initHttpHeader(context);
        initDeviceId(context);
        initDisplayInfo(context);
        initPrefAndGson(context);
        initVersionInfo(context);
        initRequestQueue(context);
        loadUserInfo();
    }

    //api接口环境调用控制开关
    private static void initDomain(Context context) {
        domain = context.getString(isDebug ? R.string.domain : R.string.test_domain);//可以获取string.xml中定义的字符串
        L.d("domain", "domain:" + domain);
    }

    private static void initAppDataFolderPath(Context context) {
        packageName = context.getPackageName();//context.getClass和getPackageName的区别,一个是取得类名，一个是取得包名。
        appDataFolderPath = Environment.getExternalStorageDirectory() + "/"
                + packageName;
        imagesFolder = appDataFolderPath + "/images";
        File pf = new File(imagesFolder);
        if (!pf.exists())
            pf.mkdirs();
        downloadFolder = appDataFolderPath + "/download";
        File df = new File(downloadFolder);
        if (!df.exists())
            df.mkdirs();
        webappFolder = appDataFolderPath + "/webapp";
        File wf = new File(webappFolder);
        if (!wf.exists())
            wf.mkdirs();
    }

    private static void initHttpHeader(Context context) {
        headers = new HashMap<>();
        // putHeader("Content-Type", "application/json;charset=utf-8");
        putHeader("ApiKey", apiKey);
        putHeader("AppOwnerId", appOwnerId);
    }

    private static void putHeader(String key, String value) {
        headers.put(key, value);
    }

    private static void initDeviceId(Context context) {
        deviceId = TelephoneUtil.getLocalDeviceId(context);
        putHeader("DeviceId", deviceId);
        L.d("DeviceId", deviceId);
    }

    private static void initDisplayInfo(Context context) {
        mDisplayWidth = ScreenUtil.getDisplayWidth(context);
        mDisplayHeight = ScreenUtil.getDisplayHeight(context);
    }

    private static void initPrefAndGson(Context context) {
        mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        mEditor = mPrefs.edit();
        mGson = new Gson();
    }

    private static void initVersionInfo(Context context) {
        VERSION_CODE = getVersionCode(context);
        VERSION_NAME = getVersionName(context);
        putHeader("ClientVersion", VERSION_NAME);
    }

    private static int getVersionCode(Context context) {
        try {
            return VersionUtil.getVersionCode(context);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    private static String getVersionName(Context context) {
        try {
            return VersionUtil.getVersionName(context);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return context.getString(R.string.default_version_name);
    }

    private static void initRequestQueue(Context context) {
        mVolleyQueue = Volley.newRequestQueue(context);
    }

    private static void loadUserInfo() {
        L.d("user info", getString(Key.USER_INFO, toJson(new User())));
        mUser = fromJson(getString(Key.USER_INFO, toJson(new User())),
                User.class);
        if (isLogin())
            setAuthToken(mUser.getToken());
    }

    public static boolean isLogin() {
        return mUser.isLogin();
    }

    public static void login(User user) {
        user.setIsLogin(true);
        setAuthToken(user.getToken());//
        saveUserInfo(user);
    }

    public static void logout() {
        removeAuthToken();
        saveUserInfo(new User());
    }

    public static void setAuthToken(String token) {
        L.d("AuthToken", token);
        putHeader("AuthToken", token);
    }

    public static void removeAuthToken() {
        removeHeader("AuthToken");
    }

    private static void removeHeader(String key) {
        headers.remove(key);
    }

    //更新&保存用戶信息
    private static void saveUserInfo(User user) {
        mUser.update(user);
        updateUserInfo();
    }

    //更新本地用戶信息
    public static void updateUserInfo() {
        putString(Key.USER_INFO, toJson(mUser));
    }

    public static void putString(String key, String value) {
        mEditor.putString(key, value).commit();
    }

    public static String getString(String key, String defValue) {
        return mPrefs.getString(key, defValue);
    }

    public static void putBoolean(String key, boolean value) {
        mEditor.putBoolean(key, value).commit();
    }

    public static boolean getBoolean(String key, boolean defValue) {
        return mPrefs.getBoolean(key, defValue);
    }

    public static void putLong(String key, long value) {
        mEditor.putLong(key, value).commit();
    }

    public static long getLong(String key, long defValue) {
        return mPrefs.getLong(key, defValue);
    }

    public static String toJson(Object src) {
        return mGson.toJson(src);
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        return mGson.fromJson(json, classOfT);
    }

    public static <T> T fromJson(String json, Type typeOfT) {
        return mGson.fromJson(json, typeOfT);
    }

    public static void addRequest(Request<?> request) {
        request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 1, 1.0f));
        mVolleyQueue.add(request);
    }
}
